package main

import (
	"log"
	"os"
	"path/filepath"

	"github.com/aliyun/aliyun-oss-go-sdk/oss"
)

func download(path, prefixStr string) {
	client, err := oss.New("https://oss-cn-zhangjiakou.aliyuncs.com", "LTAI4FsA8TiM6JATw1mmpvoV", "M641HGVBk2uiS2cpqS09Ul4o2ElaKg")
	if err != nil {
		log.Panicln(err)
	}

	bucket, err := client.Bucket("his-eis-ali")
	if err != nil {
		log.Panicln(err)
	}

	var restoreConfig oss.RestoreConfiguration
	restoreConfig.Tier = string(oss.RestoreExpedited)
	restoreConfig.Days = 1

	marker := oss.Marker("")
	prefix := oss.Prefix(prefixStr)
	for {
		lor, err := bucket.ListObjects(marker, prefix)
		if err != nil {
			log.Panicln(err)
		}
		log.Println("len", len(lor.Objects))
		for _, object := range lor.Objects {
			file := filepath.Join(path, object.Key[len(prefixStr)-2:])
			if PathExists(file) {
				continue
			}

			log.Println("Objects:", object.Key, file)
			err = bucket.GetObjectToFile(object.Key, file)
			if err != nil {
				log.Println(err)
			}
		}

		prefix = oss.Prefix(lor.Prefix)
		marker = oss.Marker(lor.NextMarker)
		if !lor.IsTruncated {
			break
		}
	}
}

func PathExists(path string) bool {
	if _, err := os.Stat(path); err == nil {
		return true
	}

	return false
}

func main() {
	// download("/home/ender/文档/312037", "free/parcel/2020/6")
	// download("/home/ender/文档/312037", "free/parcel/2020/7")
	// download("/home/ender/文档/312037", "free/parcel/2020/8")
	// download("/home/ender/文档/312037", "free/parcel/2020/9")
	download("/home/ender/文档/312037", "free/parcel/2020/10")
}
